//
//  VideoEditViewController.m
//  TestPrj
//
//  Created by 朱铅峰 on 2019/12/9.
//  Copyright © 2019 Xing. All rights reserved.
//

#import "VideoEditViewController.h"
#import "PickerVideoView.h"
#import <AVKit/AVKit.h>
#import "AudioPlayerManager.h"
#import <TZImageManager.h>
#import <Photos/Photos.h>
#import "SLVideoTool.h"
#import <Toast.h>

@interface VideoEditViewController ()<SLVideoToolDelegate>

proStrong NSURL *defaultAudioUrl;
proStrong NSURL *defaultVideoUrl;

proStrong UIControl *defaultVideoControl;
proStrong UIImageView *defaultVideoImageView;

proStrong UIControl *defaultAudioControl;
proStrong UIImageView *defaultAudioStateIcon;
proStrong PickerVideoView *pickerView;

proCopyString mixedFilePath;
proAssign BOOL isMixVideo;
proCopyString clipFilePath;
proAssign BOOL isClipVideo;
proCopyString appendFilePath;
proAssign BOOL isAppendVideo;

proStrong SLVideoTool *currentVideoTool;

@end

@implementation VideoEditViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.title = @"视频简单编辑操作(AVFoundation)";
    self.view.backgroundColor = [UIColor whiteColor];
    
    UILabel *dVideoLabel = [Utils genLabelWithFrame:CGRectMake(10, kNavBarHeight+10, 80, 50) textAlign:NSTextAlignmentLeft fontSize:14 textColor:kColorBlack];
    dVideoLabel.text = @"原始视频:";
    [self.view addSubview:dVideoLabel];
    
    _defaultVideoControl = [[UIControl alloc] initWithFrame:CGRectMake(100, kNavBarHeight+10, 50, 50)];
    [Utils resetView:_defaultVideoControl bgColor:kColorBlack cornerRadius:5 borderWidth:0.5 borderColor:kColorLineColor];
    [self.view addSubview:_defaultVideoControl];
    _defaultVideoImageView = [[UIImageView alloc] initWithFrame:_defaultVideoControl.bounds];
    _defaultVideoImageView.backgroundColor = kColorBlack;
    _defaultVideoImageView.contentMode = UIViewContentModeScaleAspectFit;
    [_defaultVideoControl addSubview:_defaultVideoImageView];
    [_defaultVideoControl addTarget:self action:@selector(videoControlAction) forControlEvents:UIControlEventTouchUpInside];
    UIImageView *defaultAudioStateIcon = [[UIImageView alloc] initWithFrame:CGRectMake((_defaultVideoControl.width-24)/2, (_defaultVideoControl.height-24)/2, 24, 24)];
    defaultAudioStateIcon.image = [UIImage imageNamed:@"play_start_icon.png"];
    [_defaultVideoControl addSubview:defaultAudioStateIcon];
    
    UILabel *dAudioLabel = [Utils genLabelWithFrame:CGRectMake(10, dVideoLabel.bottom+10, 80, 50) textAlign:NSTextAlignmentLeft fontSize:14 textColor:kColorBlack];
    dAudioLabel.text = @"原始音频:";
    [self.view addSubview:dAudioLabel];
    
    _defaultAudioControl = [[UIControl alloc] initWithFrame:CGRectMake(100, dAudioLabel.top, 50, 50)];
    [Utils resetView:_defaultAudioControl bgColor:kColorBlack cornerRadius:5 borderWidth:0.5 borderColor:kColorLineColor];
    [self.view addSubview:_defaultAudioControl];
    _defaultAudioStateIcon = [[UIImageView alloc] initWithFrame:CGRectMake((_defaultAudioControl.width-24)/2, (_defaultAudioControl.height-24)/2, 24, 24)];
    _defaultAudioStateIcon.image = [UIImage imageNamed:@"play_start_icon.png"];
    [_defaultAudioControl addSubview:_defaultAudioStateIcon];
    [_defaultAudioControl addTarget:self action:@selector(audioControlAction) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *otherLabel = [Utils genLabelWithFrame:CGRectMake(10, _defaultAudioControl.bottom+10, 200, 20) textAlign:NSTextAlignmentLeft fontSize:14 textColor:kColorBlack];
    otherLabel.text = @"其他视频:";
    [self.view addSubview:otherLabel];
    
    _pickerView = [[PickerVideoView alloc] initWithFrame:CGRectMake(10, otherLabel.bottom+10, self.view.width-20, [PickerVideoView viewHeight])];
    _pickerView.targetVC = self;
    [Utils resetView:_pickerView bgColor:[UIColor whiteColor] cornerRadius:5 borderWidth:1 borderColor:kColorBlack];
    [self.view addSubview:_pickerView];
    
    UIButton *mixAudioBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    mixAudioBtn.frame = CGRectMake(10, _pickerView.bottom+15, 70, 30);
    mixAudioBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [mixAudioBtn setTitle:@"混音处理" forState:UIControlStateNormal];
    [mixAudioBtn addTarget:self action:@selector(mixAudioBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:mixAudioBtn];
    
    UIButton *appendVideoBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    appendVideoBtn.frame = CGRectMake(10, mixAudioBtn.bottom+15, 70, 30);
    appendVideoBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [appendVideoBtn setTitle:@"视频拼接" forState:UIControlStateNormal];
    [appendVideoBtn addTarget:self action:@selector(appendVideosBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:appendVideoBtn];
    
    UIButton *clipVideoBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    clipVideoBtn.frame = CGRectMake(10, appendVideoBtn.bottom+15, 70, 30);
    clipVideoBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [clipVideoBtn setTitle:@"视频裁剪" forState:UIControlStateNormal];
    [clipVideoBtn addTarget:self action:@selector(clipVideosBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:clipVideoBtn];
    
    [self setup];
}

/// 初始化
- (void)setup {
    
    WEAKSELF
    self.defaultAudioUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"audio" ofType:@"mp3"]];//28s
    self.defaultVideoUrl = [[NSBundle mainBundle] URLForResource:@"video" withExtension:@"mp4"];
    
    //混音缓存路径
    NSString *videoFileName = @"MixedVideo.mp4";
    _mixedFilePath = [kCachePath stringByAppendingPathComponent:videoFileName];
    //拼接缓存路径
    NSString *appendFileName = @"AppendedVideo.mp4";
    _appendFilePath = [kCachePath stringByAppendingPathComponent:appendFileName];
    //剪辑缓存路径
    NSString *clipFileName = @"ClipedVideo.mp4";
    _clipFilePath = [kCachePath stringByAppendingPathComponent:clipFileName];
    
    //初始视频封面图
    UIImage *defaultVideoImage = [Utils getVideoPreviewImage:self.defaultVideoUrl.path];
    self.defaultVideoImageView.image = defaultVideoImage;

    [[AudioPlayerManager sharedInstance] setDidFinishAction:^{
        [weakSelf stopPlayAudioAction];
    }];
}


/// 播放原始视频
- (void)videoControlAction {
    
    WEAKSELF
    _defaultVideoControl.userInteractionEnabled = NO;
    
    AVPlayerViewController *playerVC = [[AVPlayerViewController alloc] init];
    playerVC.player = [[AVPlayer alloc] initWithURL:self.defaultVideoUrl];
    playerVC.modalPresentationStyle = UIModalPresentationFullScreen;
    
    [self presentViewController:playerVC animated:YES completion:^{
        if ([playerVC isReadyForDisplay]) {
            [playerVC.player play];
        }
        weakSelf.defaultVideoControl.userInteractionEnabled = YES;
    }];
}

/// 原始音频控制器
- (void)audioControlAction {
    
    if ([[AudioPlayerManager sharedInstance] isPlaying]) {
        [self stopPlayAudioAction];
    } else {
        [self startPlayAudioAction];
    }
}
/// 播放原始音频
- (void)startPlayAudioAction {
    
    _defaultAudioStateIcon.image = [UIImage imageNamed:@"play_pause_icon.png"];
    
    [[AudioPlayerManager sharedInstance] startWithPath:[_defaultAudioUrl path]];
}
/// 停止原始音频
- (void)stopPlayAudioAction {
    
    _defaultAudioStateIcon.image = [UIImage imageNamed:@"play_start_icon.png"];
    
    [[AudioPlayerManager sharedInstance] stop];
}

/// 原始视频和原始音频混音处理
- (void)mixAudioBtnAction {
    
    WEAKSELF
    [self.view makeToastActivity:CSToastPositionCenter];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [weakSelf beginMixAudioAction];
    });
    
}
- (void)beginMixAudioAction {
    
    _isMixVideo = YES;
    
    _currentVideoTool = [[SLVideoTool alloc]initWithURL:self.defaultVideoUrl];
    _currentVideoTool.delegate = self;
    
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    [parametersDic setObject:self.defaultAudioUrl forKey:SLVideoMixingAudioParameterAudioAssetURLKey];
    [parametersDic setObject:@"0.1" forKey:SLVideoMixingAudioParameterVideoVolumeKey];
    [parametersDic setObject:@"1" forKey:SLVideoMixingAudioParameterAudioVolumeKey];
    [parametersDic setValue:[NSValue valueWithCMTime:CMTimeMake(0, 100)] forKey:SLVideoMixingAudioParameterAudioStartTimeKey];
    [parametersDic setValue:[NSValue valueWithCMTimeRange:CMTimeRangeMake(CMTimeMake(0, 100), CMTimeMake(2000, 100))] forKey:SlVideoMixingAudioParameterTimeRangeOfAudioKey];
    [parametersDic setValue:[NSValue valueWithCMTimeRange:CMTimeRangeMake(CMTimeMake(0, 100), CMTimeMake(5000, 100))] forKey:SLVideoMixingAudioParameterTimeRangeOfVideoKey];
    BOOL isMixed = [_currentVideoTool mixAudioWithParameters:parametersDic];
    if (isMixed) {
        NSLog(@"混音成功");
    } else {
        NSLog(@"混音失败");
    }
    
    NSFileManager *filrManage = [NSFileManager defaultManager];
    [filrManage removeItemAtPath:_mixedFilePath error:nil];
    [_currentVideoTool writerFile:[NSURL fileURLWithPath:_mixedFilePath]];
}

//视频裁剪
- (void)clipVideosBtnAction {
    
    _isClipVideo = YES;
    [self.view makeToastActivity:CSToastPositionCenter];
    
    WEAKSELF
    dispatch_async(dispatch_get_main_queue(), ^{
        [weakSelf clipHalfVideoAction];
    });
}
- (void)clipHalfVideoAction {
    
    _currentVideoTool = [[SLVideoTool alloc]initWithURL:self.defaultVideoUrl];
    _currentVideoTool.delegate = self;
    
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:self.defaultVideoUrl options:nil];
    CMTime duration = asset.duration;
    [_currentVideoTool clipWithTimeRange:CMTimeRangeMake(kCMTimeZero, CMTimeMake(duration.value/2, duration.timescale))];
    
    NSFileManager *filrManage = [NSFileManager defaultManager];
    [filrManage removeItemAtPath:_clipFilePath error:nil];
    [_currentVideoTool writerFile:[NSURL fileURLWithPath:_clipFilePath]];
}

///  视频拼接
- (void)appendVideosBtnAction {
    
    if (_pickerView.videoArr.count == 0) {
        [self.view makeToast:@"请添加其他视频"];
        return;
    }
    
    [self.view makeToastActivity:CSToastPositionCenter];
    [self beginAppendVideosAction];
}
- (void)beginAppendVideosAction {
    
    NSLog(@"==> paths.count:%d",(int)_pickerView.videoArr.count);
    
    _isAppendVideo = YES;
    
    _currentVideoTool = [[SLVideoTool alloc]initWithURL:self.defaultVideoUrl];
    _currentVideoTool.delegate = self;
    
    //两种处理方式都有问题，有空再来排查 cxx_test
    NSMutableArray *paths = [NSMutableArray array];
    for (PickerVideo *obj in _pickerView.videoArr) {
        [paths addObject:obj.fileURL.path];
    }
    [_currentVideoTool spliceVideoWithArray:paths type:SLVideoTransitionTypePush];
    
    //有问题
//    int i = 0;
//    for (PickerVideo *obj in _pickerView.videoArr) {
//        BOOL isCliped = [_currentVideoTool spliceOperationSpliceAssetUrl:obj.fileURL timeRange:CMTimeRangeMake(CMTimeMake(0, 60), CMTimeMake(180, 60))];
//        if (isCliped) {
//            NSLog(@"--- clip success:%d",i);
//        } else {
//            NSLog(@"--- clip fail:%d",i);
//        }
//        i++;
//    }
    
    NSFileManager *filrManage = [NSFileManager defaultManager];
    [filrManage removeItemAtPath:_appendFilePath error:nil];
    [_currentVideoTool writerFile:[NSURL fileURLWithPath:_appendFilePath]];
}


/// 显示处理完成提示
/// @param title 提示
/// @param targetPath 目标文件路径
- (void)showCompleteAlertWithTitle:(NSString *)title targetPath:(NSString *)targetPath {
    
    WEAKSELF
    [Utils showAlertWithTitle:@"请处理" content:title targetVC:self dismissBlock:^(NSInteger index) {
        if (index == 0) {
            [weakSelf playWithTargetPath:targetPath];
        } else {
            [weakSelf saveToAlbumWithPath:targetPath];
        }
    } cancelButton:@"播放" otherButtons:@[@"保存到相册"]];
}
//播放
- (void)playWithTargetPath:(NSString *)path {
    
    AVPlayerViewController *playerVC = [[AVPlayerViewController alloc] init];
    playerVC.player = [[AVPlayer alloc] initWithURL:[NSURL fileURLWithPath:path]];
    playerVC.modalPresentationStyle = UIModalPresentationFullScreen;
    
    [self presentViewController:playerVC animated:YES completion:^{
        if ([playerVC isReadyForDisplay]) {
            [playerVC.player play];
        }
    }];
}
//保存到相册
- (void)saveToAlbumWithPath:(NSString *)path {
    
    UISaveVideoAtPathToSavedPhotosAlbum(path, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
}
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    
    [Utils showAlertViewWithTitle:@"编码完毕" content:@"已写入系统相册" buttonTitle:@"好的" targetVC:self];
}

#pragma mark -
#pragma mark SLVideoToolDelegate
- (void)synthesisResult:(BOOL)result {
    
    NSLog(@"==> synthesisResult:%@",result?@"YES":@"NO");
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.view hideToastActivity];
    });
    
    if (result) {
        
        if (_isMixVideo) {
            _isMixVideo = NO;
            [self showCompleteAlertWithTitle:@"混音成功!" targetPath:_mixedFilePath];
        } else if (_isClipVideo) {
            _isClipVideo = NO;
            [self showCompleteAlertWithTitle:@"裁剪成功!" targetPath:_clipFilePath];
        } else if (_isAppendVideo) {
            _isAppendVideo = NO;
            [self showCompleteAlertWithTitle:@"拼接成功!" targetPath:_appendFilePath];
        }
    }
    
    _currentVideoTool = nil;
}

- (void)copyAudioSampleBufferRef:(CMSampleBufferRef)sampleBufferRef {

//    char szBuf[4096];
//    int  nSize = sizeof(szBuf);
//    if ( [self.players encoderAAC:sampleBufferRef aacData:szBuf aacLen:&nSize]) {
//        NSData *data = [NSData dataWithBytes:szBuf length:nSize];
//        NSUInteger len = [data length];
//        Byte *byteData = (Byte*)malloc(len);
//        memcpy(byteData, [data bytes], len);
//        [self.players playAudioWithData:data];
//    }

//    if (sampleBufferRef) {
//      [self.players playAudioWithSampleBufferRef:sampleBufferRef];
//    }
}


@end
